package com.dongdongshop.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 阿里云 OSS 上传工具类
 */
@Component
public class FileUpload {

    private static Logger logger = LoggerFactory.getLogger(FileUpload.class);


    public static String upload(MultipartFile image) throws IOException {
        //外网访问的EndPoint（地域节点）
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 使用你自己的accessKeyId和accessKeySecret
        String accessKeyId = "LTAI4Fz9hj2Zq9GkwMPu6oXJ";
        String accessKeySecret = "gD3waD2kRBE0TYk6SypiN4bblk9srH";
        //空间名称
        String bucketName = "dongdongshop-tyz";

        String fileName = image.getOriginalFilename();
        logger.info("上传文件名为 : [[{}]]", fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成上传文件名
        String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String objectName = sdf.format(new Date()) + "/" + finalFileName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        if (ossClient.doesBucketExist(bucketName)) {
            logger.info("您已经创建Bucket：[[{}]].", bucketName);
        } else {
            logger.info("您的Bucket不存在，创建Bucket：[[{}]]。", bucketName);
            ossClient.createBucket(bucketName);
        }
        // 上传文件到阿里云OSS服务器
        ossClient.putObject(bucketName, objectName, image.getInputStream());
        logger.info("Object：[[{}]] 存入OSS成功。", objectName);
        //获取上传后的图片地址
        // 设置URL过期时间为1年  3600l* 1000*24*365。
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 24 * 365);
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        // 关闭OSSClient。
        ossClient.shutdown();
        String urlStr = url.toString();
        logger.info("上传后图片访问路径 : {}", urlStr);
        return urlStr;
    }
}